#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QDir>
#include <qmath.h>
#include <QTime>
#include <QImage>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    mQGraphicsScene = new QGraphicsScene(this);

//    QDir dir("/home/android/Opensource/WorkSpace_Qt/SuperImageViewer/images/");
//    dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
//    dir.setSorting(QDir::Size | QDir::Reversed);

//    QFileInfoList list = dir.entryInfoList();

    int size = 80;
    int part = size/8 + 1;

    int item_x = 1920;
    for (int i = 0; i < size; ++i) {
        ImageGraphicsItem *item = new ImageGraphicsItem(i);
        LockImage *lockImage = new LockImage;
        mLockImageVector.append(lockImage);
        item->setLockImage(lockImage);
        mImageGraphicsItemVector.append(item);
        item->setPos(QPointF(item_x * i, 0));
        mQGraphicsScene->addItem(item);
    }

    for(int i=0; i<part; i++){
        if(size > 0){
            int end = size - 1;
            size = size - 8;
            int begin = size >= 0 ? size : 0;
            mUpateThreadVector.append(new QImageUpdateThread(begin, end, &mLockImageVector, this));
        }
    }

//    QRectF rect = mQGraphicsScene->sceneRect();

    ui->graphicsView->setScene(mQGraphicsScene);
//    ui->graphicsView->setSceneRect(rect);
    ui->graphicsView->setDragMode(QGraphicsView::ScrollHandDrag);

    timer.start(20, this);

    Q_FOREACH(QImageUpdateThread* thread, mUpateThreadVector) {
        thread->startUpdateImage();
    }
}

MainWindow::~MainWindow()
{
    delete ui;
    delete mQGraphicsScene;
    qDeleteAll(mUpateThreadVector);
    qDeleteAll(mImageGraphicsItemVector);
}

void MainWindow::timerEvent(QTimerEvent *e)
{
    Q_UNUSED(e)
    ui->graphicsView->viewport()->update();

    static QTime frameTick;
    static int totalFrame = 0;
    if (!(totalFrame & 31)) {
        int elapsed = frameTick.elapsed();
        frameTick.start();
        int fps = 32 * 1000 / (1 + elapsed);
        qDebug()<< QString("Raycasting (%1 FPS)").arg(fps);
    }
    totalFrame++;
}

void MainWindow::resizeEvent(QResizeEvent *event)
{
    ui->graphicsView->smallest();
}

#ifndef QT_NO_WHEELEVENT
void MainWindow::wheelEvent(QWheelEvent *e)
{
    if (e->modifiers() & Qt::ControlModifier) {
        if (e->delta() > 0){
            ui->graphicsView->zoom(false);
        } else {
            ui->graphicsView->zoom(true);
        }
        e->accept();
    } else {
        //        MainWindow::wheelEvent(e);
    }
}
#endif



